<template>
	<view>
		<view class="margin-0" style="margin:7rpx 12rpx 12rpx 12rpx;">
			<swiper class="screen-swiper square-dot" style="margin:-1rpx;" :indicator-dots="true" :circular="true"
				:autoplay="true" interval="5000" duration="500">
				<swiper-item v-for="(item,index) in swiperList" :key="index">
					<image :src="item.url" mode="aspectFill">
					</image>
				</swiper-item>
			</swiper>
		</view>
		<view>{{activateTitle}}</view>
		<view class="activate_detail">{{activateDetail}}</view>
		<view>{{activateLocation}}</view>
		<view>{{activateStarttime}}-{{activateEndtime}}</view>
		<view>历史累计运动{{histroyDistance}}m</view>
		<view>目标公里数{{targetDistance}}km</view>

		<view class="button-joinIn">
			<view class="icon-btn-item" @click="cancel()">
				<view class="sort-btn-confim">取消报名</view>
			</view>
			<view v-if="!isEnd" class="icon-btn-item" @click="join()">
				<view v-show="isJoin&&(parseFloat(targetDistance)>(parseFloat(histroyDistance)/1000))" class="sort-btn-confim"
					@click="navigateTo('/main/run/runActivate')">开始打卡跑步</view>
				<view v-show="!isJoin" class="sort-btn-confim">报名</view>
				<view v-show="isJoin&&(parseFloat(targetDistance)<(parseFloat(histroyDistance)/1000))" class="sort-btn-confim"
					@click="navigateTo('/main/run/comment')">已完成目标查看评论</view>
			</view>
			<view class="icon-btn-item" v-else>
				<view class="sort-btn-confim">活动已结束</view>
				<view class="sort-btn-confim" @click="navigateTo('/main/run/comment')">查看评论</view>
			</view>
		</view>
		<view>
			<!-- <button @click="open">打开弹窗</button> -->
			<uni-popup ref="popup" type="bottom">
				<view class="test-popup"> 活动已结束</view>
			</uni-popup>
		</view>
	</view>

</template>

<script>
	import uniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue'
	import {
		getActivateInforByID,
		joinActivate,
		cancelActivate,
		SearchCurrentIsJoinActivate
	} from "@/api/activate.js"
	import {
		uploadGps,
		getHistoryRunData
	} from '@/api/run.js'
	export default {
		components: {
			uniPopup
		},
		data() {
			return {
				activateLocation: undefined,
				safeAreaBottom: 0,
				isJoin: false,
				isEnd: false,
				activateDetail: undefined,
				activateId: null,
				swiperList: undefined,
				activateStarttime: undefined,
				activateEndtime: undefined,
				activateTitle: undefined,
				histroyDistance: 0.0,
				targetDistance: undefined,
				info: [{
						colorClass: 'uni-bg-red',
						url: 'https://th.bing.com/th/id/R.518f706706d91731bd11c5a690c38303?rik=fcJo7r0YsdZ8WQ&riu=http%3a%2f%2fpic.baike.soso.com%2fp%2f20131104%2f20131104135301-2076974441.jpg&ehk=9hoH4wi6TmozzGvEgJ7ZrDA%2bR1EzRKFBQLaOn9QkwlA%3d&risl=&pid=ImgRaw&r=0',
						content: '内容 A'
					},
					{
						colorClass: 'uni-bg-green',
						url: 'https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/shuijiao.jpg',
						content: '内容 B'
					},
					{
						colorClass: 'uni-bg-blue',
						url: 'https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/shuijiao.jpg',
						content: '内容 C'
					}
				],
				dotStyle: [{
						backgroundColor: 'rgba(0, 0, 0, .3)',
						border: '1px rgba(0, 0, 0, .3) solid',
						color: '#fff',
						selectedBackgroundColor: 'rgba(0, 0, 0, .9)',
						selectedBorder: '1px rgba(0, 0, 0, .9) solid'
					},
					{
						backgroundColor: 'rgba(255, 90, 95,0.3)',
						border: '1px rgba(255, 90, 95,0.3) solid',
						color: '#fff',
						selectedBackgroundColor: 'rgba(255, 90, 95,0.9)',
						selectedBorder: '1px rgba(255, 90, 95,0.9) solid'
					},
					{
						backgroundColor: 'rgba(83, 200, 249,0.3)',
						border: '1px rgba(83, 200, 249,0.3) solid',
						color: '#fff',
						selectedBackgroundColor: 'rgba(83, 200, 249,0.9)',
						selectedBorder: '1px rgba(83, 200, 249,0.9) solid'
					}
				],
				modeIndex: -1,
				styleIndex: -1,
				current: 0,
				mode: 'round',
				dotsStyles: {
					backgroundColor: 'rgba(0, 0, 0, .3)',
					border: '1px rgba(0, 0, 0, .3) solid',
					color: '#fff',
					selectedBackgroundColor: 'rgba(0, 0, 0, .9)',
					selectedBorder: '1px rgba(0, 0, 0, .9) solid'
				},
				swiperDotIndex: 0
			}
		},
		watch: {
			isEnd(newValue) {
				if (newValue) { // 当isEnd变为true时
					this.open(); // 调用打开弹窗的方法
				}
			}
		},
		onShow() {
			this.init()
		},
		onLoad(options) {

			// this.selectMode('round', 2)
			// this.selectStyle(3)
			this.activateId = options.acitvate
			console.log("options.activate =>", options.acitvate)
			if (options.state == "true") {
				this.isEnd = false
			} else {
				this.isEnd = true
			}
			// this.isEnd =!options.state
			// console.log("isEnd =>", this.isEnd)
			// console.log("isEnd =>", options.state)
		},
		mounted() {
			//初始化底部按钮
			// this.buttomCssInit();
			const systemInfo = uni.getSystemInfoSync();
			this.safeAreaBottom = systemInfo.safeArea.bottom;
			// document.documentElement.style.setProperty('--safe-area-inset-bottom', `${this.safeAreaBottom}px`);
			if (this.isEnd) {
				this.open()
			}
		},
		methods: {
			async init() {
				let res = await getHistoryRunData(this.$store.state.user.id, this.activateId)
				console.log("this.init =>", res)
				// 计算累计跑步多少
				res.data.data.regps.forEach((item, index) => {
					console.log(`regps item ${index}:`, item);
					if (item.gPSdata.length > 0) {
						this.histroyDistance = this.histroyDistance + this.calculateTotalDistance(item.gPSdata)
					}
					// 遍历 gPSdata
					item.gPSdata.forEach((gpsItem, gpsIndex) => {
						console.log(`gPSdata item ${gpsIndex} for regps item ${index}:`, gpsItem);
					});
				});

				let userInfo = this.$store.state.user;
				// let userInfor.id = 55;

				await this.getUserActivateIsJoin(userInfo.id, this.activateId)

				let that = this
				that.getActivateInfor(that.activateId).then(res => {
					console.log("xxxres=>", res)
					//初始化活动信息
					this.activateLocation = res.data.data.reactivate.location
					that.activateDetail = res.data.data.reactivate.details
					this.activateTitle = res.data.data.reactivate.title
					this.targetDistance = parseFloat(res.data.data.reactivate.targetDistance.split('k'))
					// this.activateEndtime = res.data.data.reactivate.endtime
					// 使用 Date 对象和 toLocaleString 方法格式化日期和时间
					let start = new Date(res.data.data.reactivate.starttime);
					let end = new Date(res.data.data.reactivate.endtime);
					this.activateStarttime = start.toLocaleString(
						'zh-CN', {
							hour12: false
						});
					this.activateEndtime = end.toLocaleString('zh-CN', {
						hour12: false
					});

					that.swiperList = [{
						"url": res.data.data.reactivate.url
					}]


					// console.log("this.activateDetail=>", that.activateDetail)
					// console.log("this.swiperList=>", that.swiperList)
				})


			},
			calculateTotalDistance(markers) {
				let totalDistance = 0;
				for (let i = 0; i < markers.length - 1; i++) {
					const distance = this.calculateDistance(
						markers[i].latitude, markers[i].longitude,
						markers[i + 1].latitude, markers[i + 1].longitude
					);
					totalDistance += distance;
				}
				return totalDistance;
			},
			calculateDistance(lat1, lon1, lat2, lon2) {
				const R = 6371e3; // 地球半径(m)
				const φ1 = lat1 * Math.PI / 180; // φ, λ 弧度制
				const φ2 = lat2 * Math.PI / 180;
				const Δφ = (lat2 - lat1) * Math.PI / 180;
				const Δλ = (lon2 - lon1) * Math.PI / 180;

				const a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
					Math.cos(φ1) * Math.cos(φ2) *
					Math.sin(Δλ / 2) * Math.sin(Δλ / 2);
				const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

				const distance = R * c; // (m)
				return distance;
			},

			navigateTo(url) {
				uni.navigateTo({
					url: `${url}?activateId=${this.activateId}`
				})
			},
			async getUserActivateIsJoin(userId, activateId) {
				let res = await SearchCurrentIsJoinActivate(userId, activateId)
				console.log("res zzzz  =>", res)
				if (res.data.msg == "没有找到匹配的记录") {
					console.log("没有找到匹配的记录")
					this.isJoin = false
				} else {
					this.isJoin = true
				}
			},
			open() {
				// 通过组件定义的ref调用uni-popup方法 ,如果传入参数 ，type 属性将失效 ，仅支持         
				//['top','left','bottom','right','center']
				this.$refs.popup.open('bottom') //底部弹出
			},
			AcitvateIsEnd() {

			},
			async cancel() {
				if (!this.isJoin) {
					uni.showToast({
						title: '没有报名，请先报名',
						icon: 'none'
					});
					return;
				}

				try {
					let userInfo = this.$store.state.user;
					// userInfo.id = 55;
					const result = await cancelActivate(userInfo.id, this.activateId);
					if (result.statusCode === 200 && result.data.code === 0) {
						this.isJoin = false;
						uni.showToast({
							title: '取消报名成功',
							icon: 'success'
						});
					} else {
						uni.showToast({
							title: '取消失败，请稍后再试',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('Error on cancelling registration:', error);
					uni.showToast({
						title: '取消失败，请检查网络',
						icon: 'none'
					});
				}
			},

			// 报名
			async join() {
				if (this.isJoin) {
					uni.showToast({
						title: '已经报名，无需再报名',
						icon: 'none'
					});
					return;
				}

				try {
					let userInfo = this.$store.state.user;
					// userInfo.id = 55;
					const result = await joinActivate(userInfo.id, this.activateId);
					if (result.statusCode === 200 && result.data.code === 0) {
						this.isJoin = true;
						uni.showToast({
							title: '报名成功',
							icon: 'success'
						});
					} else {
						uni.showToast({
							title: '报名失败，请稍后再试',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('Error on joining:', error);
					uni.showToast({
						title: '报名失败，请检查网络',
						icon: 'none'
					});
				}
			},
			async getActivateInfor(activateID) {
				// let userInfo = this.$store.state.user;
				let userInfo = 1;
				try {
					const res = await getActivateInforByID(userInfo, activateID); // 使用 await 等待异步调用结果
					console.log("res=>", res);
					if (res.statusCode === 200 && res.data.code === 0) {
						return res; // 这里的 return 将只在这个方法内部有效
					} else {
						console.error('Fetch failed with response:', res.data);
					}
				} catch (error) {
					console.error('Error fetching activation info:', error);
				}
			},
			buttomCssInit() {
				const {
					windowHeight
				} = uni.getSystemInfoSync();
				let bottomHeight = 0;
				let topHeight = 0;
				uni.getSystemInfo({
					success: function(res) {
						// res - 各种参数
						let bottom = uni.createSelectorQuery().select(".page-bottom");
						// console.log("bottom =>",bottom)
						bottom
							.boundingClientRect(function(data) {
								if (data && data.height) {
									//data - 各种参数
									bottomHeight = data.height; // 获取元素宽度
								}
							})
							.exec();
						let top = uni.createSelectorQuery().select(".header");
						top
							.boundingClientRect(function(data) {
								if (data && data.height) {
									//data - 各种参数
									topHeight = data.height; // 获取元素宽度
								}
							})
							.exec();
					},
				});

				this.productRefHeight = windowHeight - bottomHeight + "px";
			},

			change(e) {
				this.current = e.detail.current
			},
			selectStyle(index) {
				this.dotsStyles = this.dotStyle[index]
				this.styleIndex = index
			},
			selectMode(mode, index) {
				this.mode = mode
				this.modeIndex = index
				this.styleIndex = -1
				this.dotsStyles = this.dotStyle[0]
			},
			clickItem(e) {
				this.swiperDotIndex = e
			},
			onBanner(index) {
				console.log(22222, index);
			}
		}
	}
</script>

<style lang="scss">
	@import "./activate.scss";

	.button-joinIn {
		display: flex;
		position: fixed;
		bottom: var(--safe-area-inset-bottom);
		left: 50%;
		transform: translate(-50%, -50%);
		width: 100%;
		/* 自定义宽度 */
		// height: 100px;
		/* 自定义高度 */
		background-color: #eee;
		/* 自定义背景色 */

		// padding-bottom: var(--safe-area-inset-bottom);
		// padding-bottom: 0;

	}

	.icon-btn-item {
		flex: 1;
	}

	.sort-btn-confim {
		color: #fff;
		background-image: linear-gradient(90deg, #ff6b35, #ff9f28, #ffcc03);
		text-align: center;
	}

	.test-popup {
		background: white; //默认全屏时灰色，只需要把你需要的部分改成白色
		border-radius: 20px; //设置弧度的大小
		height: 200px;
		display: flex;
		/* 使用 Flex 布局 */
		align-items: center;
		/* 垂直居中 */
		justify-content: center;
		/* 水平居中 */
		font-size: 24px;
	}
</style>